package com.example.douyin.demo;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.douyin.R;

public class MyView extends View {
    Paint paint;//画笔
    int time;//设置倒计时的具体时间
    int angle;//弧度
    public MyView(Context context) {
        super(context);
        initPaint();
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    @SuppressLint("ResourceAsColor")
    private void initPaint() {
        paint = new Paint();
        paint.setAntiAlias(true);//抗锯齿化
        paint.setColor(R.color.teal_200);
        paint.setStrokeWidth(10);
        paint.setTextSize(50);
        paint.setStyle(Paint.Style.STROKE);//空心
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(""+time,50,50,paint);

        RectF f = new RectF(0, 0, 100, 100);
        canvas.drawArc(f,0,angle,false,paint);
    }

    //想要有一个动画效果  i指的是外部倒计时开始时间
    public void start(int i){
        time = i;
        {
            ValueAnimator animator = ValueAnimator.ofInt(i, 0);
            animator.setDuration(i*1000);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                    time = (int) animation.getAnimatedValue();
                    invalidate();//重新绘制
                }
            });
            animator.start();
        }
        {
            ValueAnimator animator = ValueAnimator.ofInt(-360,0);
            animator.setDuration(i*1000);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                    angle = (int) animation.getAnimatedValue();
                    invalidate();//重新绘制
                }
            });
            animator.start();
        }
    }

}
